<template>
	<view class="one" :data-theme="theme">
		<view class="scrollHeight">
			<view class="bian">
				<view class="title">法人信息</view>
				<view><text class="text-gray">依照行业规定，平台需校验营业执照法人身份信息</text></view>
				<u--form labelPosition="left" :model="merchantData" :rules="rules" ref="legalPersonForm"
					label-width="100px">

					<u-form-item label="证件类型" style="padding: 20px 10px 0;" prop="behalfCardTypeName" borderBottom
						@click="behalfCardTypeClick">
						<u--input v-model="merchantData.behalfCardTypeName" disabled disabledColor="#ffffff"
							placeholder="请选择证件类型" ab border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<view class="shangc">
						<view class="sc-l">
							<view class="sc-l-img">

								<u-upload :fileList="fileList1" @afterRead="afterRead" :disabled="merchantData.isApply"
									@delete="deletePic" name="1" multiple :maxCount="1">
									<image v-if="!cardFrontPhoto" src="../../../imgs/idFront.png" mode="heightFix"
										style="width: 140px;height: 85px;">
									</image>
									<image v-else :src="cardFrontPhoto" mode="heightFix"
										style="width: 140px;height: 85px;">
									</image>
								</u-upload>

							</view>
							<view>身份证正面</view>

						</view>
						<view class="sc-l">
							<view class="sc-l-img">
								<u-upload :fileList="fileList2" @afterRead="afterRead" :disabled="merchantData.isApply"
									@delete="deletePic" name="2" multiple :maxCount="1">

									<image v-if="!cardBackPhoto" src="../../../imgs/idReverse.png" mode="heightFix"
										style="width: 140px;height: 85px;">
									</image>
									<image v-else :src="cardBackPhoto" mode="heightFix"
										style="width: 140px;height: 85px;">
									</image>
								</u-upload>

							</view>

							<view>身份证反面</view>

						</view>
					</view>
					<u-form-item label="姓名" prop="behalfName" borderBottom>
						<u--input v-model="merchantData.behalfName" disabledColor="#ffffff"
							:disabled="merchantData.isApply" placeholder="请输入姓名" border="none"></u--input>

					</u-form-item>
					<u-form-item label="证件号" prop="behalfCardNo" borderBottom>
						<u--input v-model="merchantData.behalfCardNo" disabledColor="#ffffff"
							:disabled="merchantData.isApply" type="tel" maxlength="18" placeholder="请输入证件号"
							border="none"></u--input>

					</u-form-item>
					<u-form-item label="预留手机号" prop="behalfCall" borderBottom>
						<u--input v-model="merchantData.behalfCall" disabledColor="#ffffff"
							:disabled="merchantData.isApply" type="tel" maxlength="11" placeholder="请输入预留手机号"
							border="none"></u--input>

					</u-form-item>


				</u--form>
				<view class="indate">
					<view class="header">身份证有效期</view>
					<view class="indateList">
						<view class="indateItem" :class='certificateIndex === 0?"selectStyle":""'
							@click="certificateClick(0,certificateArray[0])">
							<view class="itemLeft">{{certificateArray[0].name}}</view>
							<view class="itemRight">{{certificateArray[0].time}}</view>
						</view>

						<view class="indateItem" :class='certificateIndex === 1?"selectStyle":""'
							@click="certificateClick(1,certificateArray[1])">
							<view class="itemLeft">{{certificateArray[1].name}}</view>
							<uni-datetime-picker type="daterange" :disabled="merchantData.isApply"
								:start="formatDate(startDate)" :end="formatDate(endDate)" rangeSeparator="至"
								@change="confirm"
								v-model="behalfValidity">{{certificateArray[1].time}}</uni-datetime-picker>
						</view>
					</view>

				</view>
				<u-action-sheet :show="showType" :actions="legalCardTypeList" title="请选择证件类型" @close="showType = false"
					@select="certificateTypeSelect">
				</u-action-sheet>

			</view>
		</view>
		<!-- <view class="btn flex flex-direction bottomStyle">
			<u-button class="cu-btn lg bg-blue" :color="bgColor" @click="editClick"
				:disabled="merchantData.isApply">{{merchantData.isApply ? '审核中' : '编辑'}}</u-button>
		<!-- </view> --> -->
		<view class="btn">
			<button class="cu-btn lg bg-blue  fonter_color"
				:style="{background : merchantData.isApply ? '#eee' :bgColor,color:merchantData.isApply ? 'black' :'#fff' }"
				@click="editClick" :disabled="merchantData.isApply">{{merchantData.isApply ? '审核中' : '编辑'}}</button>
		</view>
	</view>

</template>

<script>
	import {
		setThemeColor
	} from '../../../utils/setTheme';
	import {
		legalPersonApi,
		updateLegalPersonApi
	} from '@/api/merchant.js';
	let app = getApp();
	export default {
		data() {
			return {
				// idReverse:'../../../imgs/idReverse.png',
				bgColor: "#ffffff",
				theme: app.globalData.theme,
				merchantData: {
					behalfName: '', //法人姓名不能为空
					behalfCardNo: '', //法人身份证号不能为空
					behalfCardType: '', //证件类型不能为空
					behalfCardTypeName: '',
					cardFrontPhoto: '', //法人身份证正面不能为空
					cardBackPhoto: '', //法人身份证正面不能为空
					behalfCall: '', // 预留手机号
					behalfValidity: '', //有效期不能为空
					behalfValidityType: "", //有效期类型不能为空
				},

				cardFrontPhoto: '', //法人身份证正面不能为空
				cardBackPhoto: '', //法人身份证正面不能为空
				// 正面上传图片列表
				fileList1: [

				],
				fileList2: [],
				// 表单校验
				rules: {
					// 法人信息
					behalfName: [{
						required: true,
						message: '请输入法人姓名',
						trigger: ['blur', 'change']
					}],
					behalfCardNo: [{
						required: true,
						message: '请输入法人身份证号',
						trigger: ['blur', 'change']
					}, {
						pattern: /^\d{17}[\dXx]$/,
						message: '身份证号格式不正确',
						trigger: 'blur'
					}],
					behalfCardTypeName: [{
						required: true,
						message: '请选择证件类型',
						trigger: ['blur', 'change']
					}],

					behalfCall: [{
						required: true,
						message: '请输入证预留手机号',
						trigger: ['blur', 'change']
					}, {
						pattern: /^1[3456789]\d{9}$/,
						message: '手机号格式不正确',
						trigger: 'blur'
					}],
				},
				// 证件类型显示
				showType: false,
				// 证件类型
				legalCardTypeList: [{
						name: '中国大陆居民身份证',
						type: '1',
					},

					{
						name: '其他',
						type: '2',
					},
				],
				// 证件有效期信息
				certificateArray: [{
						name: '长期有效',
						time: ""
					},
					{
						name: '固定有效期',
						time: "请选择证件有效期"
					}
				],
				// 证件有效期标识
				certificateIndex: undefined,
				// 有效期时间的初始时间和结束时间
				startDate: new Date('1900-01-01'),
				endDate: new Date(),
				behalfValidity: [], // 有效期时间组件的v-mode值
			}
		},
		async onLoad() {
			this.bgColor = setThemeColor()
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			await this.legalPerson()
			if (this.merchantData.isApply) {
				uni.showModal({
					content: '正在审核中',
					showCancel: false, // 不显示取消按钮
					confirmText: "查看法人信息",
					success: function(res) {

					}
				});
			} else if (this.merchantData.checkStatus == 2) {
				uni.showModal({
					content: '审核通过',

					showCancel: false, // 不显示取消按钮
					confirmText: "查看法人信息",
					success: function(res) {

					}
				});
			} else if (this.merchantData.checkStatus == 3) {
				uni.showModal({
					title: "审核拒绝",
					content: `原因: ${this.merchantData.reason}`,
					showCancel: false, // 不显示取消按钮
					confirmText: "查看法人信息",
					success: function(res) {

					}
				});
			}
		},

		methods: {
			// 获取日历信息
			confirm(e) {
				this.merchantData.behalfValidity = e[0] + '-' + e[e.length - 1]
				this.certificateArray[this.certificateIndex].time = e[0] + '-' + e[e.length - 1]
			},
			// 修改有效期时间
			formatDate(date) {
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				const day = date.getDate();
				return `${year}-${month}-${day}`;
			},
			// 证件类型选择的点击事件
			behalfCardTypeClick() {
				if (!this.merchantData.isApply) {
					this.showType = true;
				}
			},
			// 身分证有效期选择
			certificateClick(index, item) {
				if (!this.merchantData.isApply) {
					if (index == 0) {
						this.certificateArray[this.certificateIndex].time = "请选择证件有效期"
					}
					this.certificateIndex = index
					this.merchantData.behalfValidityType = index + 1
				}


			},
			// 证件类型选择
			certificateTypeSelect(e) {
				this.merchantData.behalfCardTypeName = e.name
				this.merchantData.behalfCardType = e.type
				this.$refs.legalPersonForm.validateField('behalfCardTypeName')
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				console.log(this[`fileList${event.name}`])
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					if (result == null) {
						uni.showToast({
							title: "上传失败",
							icon: "none",
						})
						this.deletePic(event.index, 1);
						break;
					}
					let newStatus = {
						status: 'success',
						message: '上传成功',
						url: result,
					}



					let item = this[`fileList${event.name}`][fileListLen]


					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, newStatus))


					if (event.name == 1) {


						this.cardFrontPhoto = this.fileList1[0].url // 身份证正面

					}
					if (event.name == 2) {
						this.cardBackPhoto = this.fileList2[0].url // 身份证反面

					}
					fileListLen++
					this.fileList1 = []
					this.fileList2 = []
				}
			},
			uploadFilePromise(filePath) {
				return this.$util.uploadFilePromise(filePath, {
					url: 'upload/image',
					name: "multipart", //固定 multipart
					model: "product", //模块 用户user,商品product,微信wechat,news文章
					pid: 1, //分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列
					count: 1
				});
			},

			// 编辑
			editClick() {
				this.$refs.legalPersonForm.validate().then(async (res) => {
					delete this.merchantData.id
					delete this.merchantData.merId
					delete this.merchantData.createTime
					delete this.merchantData.updateTime
					if (!this.cardFrontPhoto) return this.$util.Tips({
						title: '请上传法人身份证正面'
					});
					if (!this.cardBackPhoto) return this.$util.Tips({
						title: '请上传法人身份证反面'
					});
					if (!this.merchantData.behalfValidity) return this.$util.Tips({
						title: '有效期不能为空'
					});
					if (!this.merchantData.behalfValidityType) return this.$util.Tips({
						title: '有效期类型不能为空'
					});
					// 格式化后端所需要的图片格式
					// 切割掉域名,端口号,协议名
					let regex = /^(?:https?:\/\/)?[^/]+\/([^/]+)/;
					this.merchantData.cardFrontPhoto = this.cardFrontPhoto.replace(regex, "$1"); // 身份证正面
					this.merchantData.cardBackPhoto = this.cardBackPhoto.replace(regex, "$1"); // 身份证反面
					uni.showModal({
						title: '提示',
						content: '确认更新吗？',
						success: async (res) => {
							if (res.confirm) {
								await this.updateLegalPerson()
							} else if (res.cancel) {
								this.$util.Tips({
									title: '已取消操作'
								})
							}
						}
					});

				}).catch(err => {
					uni.$u.toast('请您正确填写信息')
					console.log(err)
				})

			},
			// 回显数据
			async legalPerson() {
				try {
					let result = await legalPersonApi()
					if (result.code == 200) {
						let data = result.data
						if (data != null) {
							this.merchantData = data
							// 判断证件以及执照有效期显示的
							if (data.behalfValidityType == 1) {
								this.certificateIndex = 0

							}
							if (data.behalfValidityType == 2) {
								this.certificateIndex = 1
								this.certificateArray[this.certificateIndex].time = data.behalfValidity

							}
							// 证件类型
							for (let i = 0; i < this.legalCardTypeList.length; i++) {
								if (this.legalCardTypeList[i].type == data.behalfCardType) {
									this.merchantData.behalfCardTypeName = this.legalCardTypeList[i].name
									break;
								}
							}
							// 回显照片
							this.cardFrontPhoto = this.merchantData.cardFrontPhoto // 身份证正面
							this.cardBackPhoto = this.merchantData.cardBackPhoto // 身份证反面
						}
					}

				} catch (e) {
					//TODO handle the exception
					this.$util.Tips({
						title: e
					})
					console.log(e)
				}
			},
			// 修改商户入驻法人申请信息

			async updateLegalPerson() {
				uni.showLoading({
					title: '加载中',
					mask: true,
				})
				try {
					let result = await updateLegalPersonApi(this.merchantData)
					uni.navigateBack(1);
					uni.hideLoading()
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
					console.log(e)
					this.$util.Tips({
						title: e,
					})
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.bg_color {
		@include main_bg_color(theme);
	}

	::v-deep .u-form-item__body__right__content__slot {
		justify-content: center;
	}

	page {
		height: 100%;
	}


	.text_color {
		@include main_color(theme)
	}

	.bottomStyle {
		position: sticky !important;
		;
		bottom: 0px !important;
		left: 0px !important;
	}

	.selectStyle {
		@include main_color(theme) @include border_color(theme);
		border: 1rpx solid;
	}

	.bg_color {
		@include main_bg_color(theme);

	}


	.scrollHeight {
		flex: 1;
	}

	.one {
		display: flex;
		flex-direction: column;
		height: 100%;

		.BH5 {
			background-color: #F3F5F4;
			height: 4px;
		}

		.title {
			padding: 5px 0 15px;
			font-weight: 600;

			span {
				color: #E74949;
				padding-right: 5px;
			}
		}

		.position {
			display: flex;
			justify-content: space-between;
			padding: 5px 0 0;

			input {
				text-align: right;
			}
		}

		.bian {
			border-bottom: 1px solid #F7F7F7;
			background-color: white;
			padding: 10px 10px 20px;
			border-radius: 10px;

			.indate {
				display: flex;
				justify-content: space-around;
				padding: 20px 0;

				.header {
					width: 100px;
				}

				.indateList {
					display: flex;

					.indateItem {
						background-color: #eee;
						padding: 10px;
						line-height: 20px;
						width: 120px;
						padding-left: 10px;
						border-radius: 10px;
						margin-right: 10px;

					}
				}



			}
		}

		.shangc {
			display: flex;
			justify-content: center;
			padding: 20px 0;

			.sc-l {
				width: 48%;
				// text-align: center;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				color: #A1A1A1;

				.sc-l-img {
					padding: 10px 0;

					img {
						width: 140px;
						height: 85px;
					}
				}
			}
		}

		.yyzz {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: 15px;


			img {
				width: 160px;
				height: 100px;
			}
		}

		.H50 {
			height: 50px;
		}

		.btn {
			position: fixed;
			bottom: 0;
			left: 0;
			padding: 10px;
			width: 100%;
			background-color: #fff;
			z-index: 9;

			.fonter_color {
				font-weight: bold;
				border-radius: 10px;
				color: #FFF;
				padding: 20rpx;
			}
		}
	}
</style>